package org.glorylight.hacks.social.controller;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.glorylight.hacks.social.data.ScrapBookCommentsData;
import org.glorylight.hacks.social.service.CommentService;
import org.glorylight.hacks.social.service.ScrapBookService;
import org.glorylight.hacks.social.util.UUIDHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
@Path("/comments")
public class CommentController extends AbstractBaseController {
	
	private static final Logger log = LoggerFactory.getLogger(CommentController.class);
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private ScrapBookService scrapBookService;
	
	@POST
	@Path("/add/{scrapId}")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public List<ScrapBookCommentsData> addComments(@PathParam("scrapId") String scrapId, @FormParam("comment") String comment) {
		String emailId = getActiveLogin();
		try {
			commentService.addComment(emailId, UUIDHelper.stringToUUID(scrapId), comment);
		} catch (Exception e) {
			log.error("can not add new comment to scrapId : {}", scrapId, e);
		}
		return scrapBookService.find(UUIDHelper.stringToUUID(scrapId)).getComments();
	}
	
	@POST
	@Path("/update/{scrapId}")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public List<ScrapBookCommentsData> updateComments(@PathParam("scrapId") String scrapId, 
			@FormParam("commentId") String commentId, @FormParam("comment") String newComment) {
		String emailId = getActiveLogin();
		try {
			commentService.updateComment(emailId, UUIDHelper.stringToUUID(commentId), newComment);
		} catch (Exception e) {
			log.error("can not update comment to scrapId : {}", scrapId, e);
		}
		return scrapBookService.find(UUIDHelper.stringToUUID(scrapId)).getComments();
	}
	
	@POST
	@Path("/delete/{scrapId}")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public List<ScrapBookCommentsData> deleteComments(@PathParam("scrapId") String scrapId, 
			@FormParam("commentId") String commentId) {
		String emailId = getActiveLogin();
		try {
			commentService.deleteComment(emailId, UUIDHelper.stringToUUID(commentId));
		} catch (Exception e) {
			log.error("can not delete comment to scrapId : {}", scrapId, e);
		}
		return scrapBookService.find(UUIDHelper.stringToUUID(scrapId)).getComments();
	}
	
}
